package com.nineclock.attendance.task;

import com.nineclock.attendance.mapper.AttendGroupMapper;
import com.nineclock.attendance.pojo.AttendGroup;
import com.nineclock.system.dto.SysCompanyUserDTO;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.File;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@Component
@Slf4j
public class SendAttendMailTask {
    @Autowired
    private JavaMailSender javaMailSender;
    @Autowired
    private AttendGroupMapper attendGroupMapper;
    @Value("${spring.mail.username}")
    private String from;
    //TODO xxlJob
    @XxlJob("countAttendanceAndSendMail")
    public void countAttendanceAndSendMail() throws Exception {

        log.info("----开始执行定时任务，发送考勤数据邮件给企业管理员----");

        // 1.获取所有设置了考勤组的企业id集合

        // 2.遍历所有的企业id，依次生成考勤报表，并发送邮件


                // 2.1 生成企业的考勤报表


                // 2.2 获取企业主管理员信息



                    // 2.3 发送邮件

    }
    /**
     * 发邮件给企业主管理员
     */
    private void sendMail(SysCompanyUserDTO companyUserDTO , String excelFile) throws MessagingException {
        MimeMessage mimeMessage = javaMailSender.createMimeMessage();
        MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage, true);
        messageHelper.setFrom(from);
        messageHelper.setTo(companyUserDTO.getEmail());
        messageHelper.setSubject("考勤数据报表");
        messageHelper.setText("您好, 本月考勤数据报表已经生成, 请查收附件, 谢谢");
        messageHelper.addAttachment("本月考勤数据.xls", new File(excelFile));
        javaMailSender.send(mimeMessage);
    }
    /**
     * 获取所有设置了考勤组的企业id集合
     */
    private Set<Long> getAllCompanyIdList(){
        List<AttendGroup> attendGroupList = attendGroupMapper.selectList(null);
        if (!CollectionUtils.isEmpty(attendGroupList)){
            return attendGroupList.stream().map(attendGroup -> {
                return attendGroup.getCompanyId();
            }).collect(Collectors.toSet());
        }
        return null;
    }
}
